<template>
  <el-card class="dept-modal-row" shadow="never">
    <el-tree
      ref="tree"
      v-if="treeData.length"
      node-key="key"
      :props="defaultProps"
      :data="treeData"
      @node-click="handleNodeClick"
      @check="handleTreeCheck"
      :show-checkbox="checkable"
      :defaultExpandAll="defaultExpandAll"
    >
      <span slot-scope="{node,data}">
        <i :class="data.icon"></i>
        <span style="padding-left: 4px;">{{node.label}}</span>
      </span>
    </el-tree>
  </el-card>
</template>

<script>
export default {
  props: {
    treeData: {
      type: Array,
      required: true
    },
    checkable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultExpandAll: false,
      checkedKeys: [],
      selectedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      mdl: {}
    }
  },
  watch: {
    treeData: {
      handler(n, o) {
        this.addIcon(n)
      },
      deep: true
    }
  },
  methods: {
    addIcon(arr) {
      arr.map(v => {
        v.icon = 'el-icon-s-flag'
        if (v.children.length > 0) {
          this.addIcon(v.children)
        }
      })
      return arr
    },
    getKeys(arr) {
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(arr)
      })
    },
    handleTreeCheck(obj1, obj2) {
      // console.log('el-tree check', obj1, obj2)
      this.checkedKeys = obj2.checkedKeys
      this.$emit('treeCheck', this.checkedKeys)
    },
    handleNodeClick(info, info2, info3) {
      console.log('info', info, info2, info3)
      if (this.mdl.key === info.key) {
        // 两次相同点击
        let selectObj = { parentName: '', parentId: '' }
        this.$nextTick(() => {
          this.$emit('changeTree', selectObj)
        })
      } else {
        // 两次不同点击
        this.mdl = { ...info }
        let selectObj = { parentName: info.title, parentId: info.key }
        this.$nextTick(() => {
          this.$emit('changeTree', selectObj)
        })
      }
    }
  }
}
</script>
